<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click=" dialogVisible=true">上传视频</el-button>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <div class="content">
        <el-upload
          :http-request="Upload"
          :before-upload="beforeAvatarUpload"
          :on-preview="handlePreview"
          :before-remove="beforeRemove"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :on-exceed="handleExceed"
          :limit="limit"
          :file-list="fileList"
          action
          drag
          class="editor-slide-upload"
        >
          <i class="el-icon-upload"/>
          <div class="el-upload__text">
            将视频文件拖到此处，或
            <em>点击上传</em>
            <br>
            <p>视频仅支持MP4格式</p>
          </div>
          <div slot="tip" class="el-upload__tip">上传文件大小不能超过 1G</div>
        </el-upload>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-progress
          v-show="showProgress"
          :text-inside="true"
          :stroke-width="15"
          :percentage="progress"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { client } from '@/utils/alioss' // 前面的ali-js文件内的两个封装函数
export default {
  name: 'Upload',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      vedioList: [],
      dialogVisible: false,
      fileList: [], // 文件列
      listObj: {},
      showProgress: false, // 进度条的显示
      dataObj: {}, // 存签名信息
      progress: 0, // 进度条数据
      bburl: ''
    }
  },
  methods: {
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },
    handleSubmit() {
      console.log('dsdsdsdsd', this.listObj)
      console.log('dsdsdsdsd视频地址', this.bburl) // 视频地址
      // const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      // console.log('tijiao ooooo', arr)
      // return false
      const vedioUrl = this.bburl
      // if (!this.checkAllSuccess()) {
      //   this.$message('请等待所有文件上传成功 或 出现了网络问题，请刷新页面重新上传！')
      //   return
      // }
      this.$emit('setContentVideo', vedioUrl)
      this.listObj = this.bburl
      this.dialogVisible = false
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`每次只能上传 ${this.limit} 个文件`)
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {},
    // 删除文件之前的钩子
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {},
    // 文件上传成功时的钩子
    handleSuccess(response, file, fileList) {
      this.fileList = fileList
      console.log('const fileList222', this.fileList)

      const uid = file.file.uid
      console.log('const uid2222222', uid)

      const objKeyArr = Object.keys(this.listObj)
      console.log('response=======', response)
      console.log('objKeyArr', objKeyArr)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url = this.bburl
          this.listObj[objKeyArr[i]].hasSuccess = true
          return
        }
      }
    },
    // 文件上传前的校验
    beforeAvatarUpload(file) {
      const isLt100M = file.size / 1024 / 1024 > 10 && file.size / 1024 / 1024 < 1024
      const isLt30 = file.name.length < 30
      console.log('file=============', file)
      if (file.type != 'video/mp4') {
        this.$message.error('请上传正确的视频格式')
        return false
      }
      if (!isLt100M) {
        this.$message.error('上传视频大小要在10MB~1GB之间哦!')
        return false
      }
      if (!isLt30) {
        this.$message.error('上传视频文件名称长度必须要小于30个文字哦!')
        return false
      }
      // console.log('beforeAvatarUpload->file.name', file.name)
      // 请求后台接口拿配置参数
      return new Promise((resolve, reject) => {
        resolve(true)
      })

      // const _self = this
      // const _URL = window.URL || window.webkitURL
      // const fileName = file.uid + 'shipin'
      // this.listObj[fileName] = {}
      // return new Promise((resolve, reject) => {
      //   const img = new Image()
      //   img.src = _URL.createObjectURL(file)
      //   console.log('img', img.src)
      //   img.onload = function() {
      //     _self.listObj[fileName] = { hasSuccess: false, uid: file.uid, width: this.width, height: this.height }
      //   }
      //   resolve(true)
      // })
    },
    // http-request属性来覆盖默认的上传行为（即action="url"），自定义上传的实现
    Upload(file) {
      const that = this
      console.log('upload================', file)
      const fileName = file.file.uid + 'shipin'
      client().multipartUpload(fileName, file.file, { progress: function(val) {
        console.log('valval', val)
        that.showProgress = true
        that.progress = Math.floor(val * 100)
      } }).then((result) => {
        if (result.res.requestUrls[0].indexOf('?') != -1) {
          this.bburl = result.res.requestUrls[0].split('?')[0]
        } else {
          // console.log('图片100k以内')
          this.bburl = result.res.requestUrls[0]
        }
        console.log('result=============', result)
        this.handleSuccess(result, file)
      }).catch((err) => {
        that.$message.error('视频上传失败，原因' + err)
      })
      // async function multipartUpload() {
      //   const temporary = file.file.name.lastIndexOf('.')
      //   const fileNameLength = file.file.name.length
      //   // const fileFormat = file.file.name.substring(
      //   //   temporary + 1,
      //   //   fileNameLength
      //   // )
      //   // const fileName = getFileNameUUID() + '.' + fileFormat
      //   // console.log('fileName', fileName)
      //   // client(that.dataObj)
      //   //   .multipartUpload(`${fileName}`, file.file, {
      //   //     progress: function(p) {
      //   //       // p进度条的值
      //   //       console.log('p=================', p)
      //   //       that.showProgress = true
      //   //       that.progress = Math.floor(p * 100)
      //   //     }
      //   //   })
      //   //   .then(result => {
      //   //     // 上传成功返回值，可针对项目需求写其他逻辑
      //   //     console.log('上传成功返回值', result)
      //   //     this.vedioList = result
      //   //   })
      //   //   .catch(err => {
      //   //     console.log('err:', err)
      //   //   })
      // }
      // multipartUpload()
    }
  }
}
</script>
